<template>
  <el-card class="trade-card">
    <el-button :icon="Plus" type="primary" @click="addTrademark" v-has="`btn.Trademark.add`">添加品牌</el-button>
    <!-- 表格 -->
    <el-table style="margin: 10px 0;" border :data="trademarkArr">
      <el-table-column label="序号" align="center" type="index" width="80px"></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO">
        <template #default="{row}">
          <img :src="row.logoUrl" style="width: 100px;height:100px;" >
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #default="{row}">
          <el-button type="warning" size="small" @click="updateTrademark(row)" :icon="Edit"></el-button>
          <el-popconfirm @confirm="deleteTrademark(row.id)" icon="Delete" width="200" :title="`确定删除${row.tmName}吗?`">
            <template #reference>
              <el-button  type="danger" size="small" :icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="limit"
      :page-sizes="[3, 5, 7, 9]"
      :small="true"
      layout=" prev, pager, next, jumper,->,total, sizes,"
      :total="total"
      background
      @current-change="getHasTrademark"
      @size-change="sizeChange"
    />
    <!-- 对话框组件: 添加修改品牌 -->
    <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id?'修改品牌':'添加品牌'" width="500">
      <el-form ref="fromRef" :rules="rules" :model="trademarkParams" style="width:80%">
        <el-form-item prop="tmName" label-width="100px" label="品牌名称">
          <el-input v-model="trademarkParams.tmName"  placeholder="请输入品牌名称"></el-input>
        </el-form-item>
        <el-form-item prop="logoUrl" label-width="100px" label="品牌LOGO">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img style="width: 178px;height: 178px;" v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽footer -->
      <template #footer>
        <el-button type="default" @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
  
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqHasTrademark, reqAddOrUpdateTrademark, reqDeleteTrademark } from '@/api/product/trademark'
import type { Records, Trademark } from '@/api/product/trademark/type'


const fromRef = ref()
// 当前页码
const pageNo = ref<number>(1)
// 每页条数
const limit = ref<number>(3)
// 数据总数
const total = ref<number>(0)
// 存储已有品牌数据
const trademarkArr = ref<Records>([])
// 收集新增或修改品牌的数据
const trademarkParams = reactive<Trademark>({
  tmName: '',
  logoUrl: ''
})
// 获取数据
const getHasTrademark = async() => {
  const res = await reqHasTrademark(pageNo.value, limit.value)
  if(res.code == 200) {
    total.value = res.data.total
    trademarkArr.value = res.data.records
  }
}
// const getHasTrademark = async(pager = 1) => {
  // onmouned 和 sizechange pager =1
  // 注意: 点击页码 getHasTrademark是currentChange回调 会自动传入当前pageNo为pager的值
  // pageNo.value = pager 
//   const res = await reqHasTrademark(pageNo.value, limit.value)
//   if(res.code == 200) {
//     total.value = res.data.total
//     trademarkArr.value = res.data.records
//   }
// }
// 页码改变 回传了当前页码
// const changePageNo = (pageNo) => {
//   getHasTrademark()
// }

// 每页数据量变化 页码归一
const sizeChange = () => {
  pageNo.value = 1
  getHasTrademark()
}

// 控制对话框显示隐藏
const dialogFormVisible = ref<boolean>(false)
// 添加品牌
const addTrademark = () => {
  // 先清空数据 和 校验结果
  clearTrademarkParams()
  clearRulesResult()
  dialogFormVisible.value = true
}
// 修改品牌
const updateTrademark = (row: Trademark) => {
  clearRulesResult()
  dialogFormVisible.value = true
  Object.assign(trademarkParams, row)
}
// 清空数据和校验结果
const clearRulesResult = () => {
  // 清空校验结果 dialog第一次出现之前 获取不到formRef  或者使用nextTick
  // fromRef.value?.clearValidate('tmName')
  // fromRef.value?.clearValidate('logoUrl')
  nextTick(()=>{
    fromRef.value.clearValidate('tmName')
    fromRef.value.clearValidate('logoUrl')
  })
}
const clearTrademarkParams = () => {
  Object.assign(trademarkParams, {tmName:'',logoUrl: '', id: 0})
}
// 对话框取消 按钮
const cancel = () => {
  dialogFormVisible.value = false
  // clearTrademarkParams()
}

// 对话框确定按钮

const confirm = async () => {
  // 对表单校验
  
  const res2 = await fromRef.value.validate()
  let res = await reqAddOrUpdateTrademark(trademarkParams)
  if(res.code == 200) {
    dialogFormVisible.value = false
    ElMessage({
      type: 'success',
      message: trademarkParams.id?'修改品牌成功~':'添加品牌成功~'
    })
    // 添加回到第一页|修改留在当前页
    if(!trademarkParams.id) {
      pageNo.value = 1
    }
    getHasTrademark()
    //清空数据
    // clearTrademarkParams()
  } else {
    ElMessage({
      type: 'error',
      message: trademarkParams.id?'修改失败~':'添加失败~'
    })
  }
}

// 上传图片之前触发 rawFile:上传的文件对象
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
    if(rawFile.size/1024/1024 < 4) {
      return true
    } else {
      ElMessage.error('文件大小不能超过4M')
      return false
    }
  } else {
    ElMessage.error('文件格式必须是PNG|JPG|GIF')
    return false
  }
}

// 上传成功的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = ( response,uploadFile) => {
  // response是上传成功返回的数据
  // uploadFile也是返回的图片信息 但包含图片名字 字节大小等
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  trademarkParams.logoUrl = response.data
  // 清除图片校验结果 logo不能为空
  fromRef.value.clearValidate()
}

// 表单校验

const validatorTmName = (rule:any, value:any, callBack:any) => {
  // 自定义校验规则
  if(value.trim().length >=2) {
    callBack()
  } else {
    callBack(new Error('品牌名称字数要大于等于2位~'))
  }
}

const validatorLogoUrl = (rule:any, value:any, callBack:any) => {
  console.log(value)
  if(value) {
    callBack()
  } else {
    callBack(new Error('上传图片不能为空~'))
  }
}

const rules = {
  tmName: [
    {required: true, trigger: 'change', validator: validatorTmName}
  ],
  logoUrl: [
    {required: true,  validator: validatorLogoUrl}
  ]
}

// 气泡确认框确认按钮回调,删除trademark
const deleteTrademark = async (id: number) => {
  const res = await reqDeleteTrademark(id)
  if(res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功~'
    })
    // 重新获取数据 如果只有一条数据的页面 页码得减一
    if(trademarkArr.value.length <=1) {
      // pageNo.value = pageNo.value-1
      pageNo.value = pageNo.value - 1 <=1?1:pageNo.value - 1
    }
    getHasTrademark()
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败~'
    })
  }
}

onMounted(()=>{
  getHasTrademark()
})

</script>

<style lang="scss" >
.trade-card {
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}

</style>
